package com.Blog.www.servlet;

import com.Blog.www.constant.DataConstant;
import com.Blog.www.constant.PageConstant;
import com.Blog.www.constant.SqlConstant;
import com.Blog.www.constant.TipsConstant;
import com.Blog.www.po.*;
import com.Blog.www.service.*;
import com.Blog.www.service.Impl.*;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;


/**
 * 博客相关的servlet
 *
 * @author 君未洋
 */
@WebServlet("/UserBlog/*")
@MultipartConfig
public class BlogServlet extends BaseServlet {

    private static UserService userService = new UserServiceImpl();
    private static BlogService blogService = new BlogServiceImpl();
    private static LikeService likeService = new LikeServiceImpl();
    private static CommentService blogCommentService = new CommentServiceImpl();
    private static ColumnService columnService = new ColumnServiceImpl();
    private static FriendService friendService = new FriendServiceImpl();
    private static LabelService labelService = new LabelServiceImpl();

    public void authorHome(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取用户的id数据
        Integer id = Integer.parseInt(req.getParameter("id"));
        //通过id获取作者信息和文章信息
        User user = userService.autoLogin(id);
        User loginUser = (User) req.getSession().getAttribute(DataConstant.USER_A);
        String labelPrior = req.getParameter("labelPrior");

        req.setAttribute(DataConstant.AUTHOR_FLAG, friendService.findFriend(loginUser.getId(), user.getId()));
        req.setAttribute(DataConstant.AUTHOR_COUNT, friendService.friendCount(user.getId()));
        req.setAttribute(DataConstant.LABEL_PAGE, labelService.getLabelPage(id, labelPrior));
        req.setAttribute(DataConstant.BLOG_L, blogService.findUserBlog(req.getParameter("currentPage"), req.getParameter("rows"), id, labelPrior));
        req.setAttribute(DataConstant.USER_F, user);
        req.setAttribute(DataConstant.BLOG_G, req.getParameter("bid"));
        req.setAttribute(DataConstant.LABEL_PRIOR, labelPrior);

        req.getRequestDispatcher("/authorHome.jsp").forward(req, resp);

    }

    public void addImg(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取上传的用户id
        //获取part对象
        Part part = req.getPart("imgFile");
        String bid = req.getParameter("bid");
        String uid = req.getParameter("uid");
        req.removeAttribute(PageConstant.BLOG_G);
        if (blogService.addImg(part, bid)) {
            req.setAttribute(PageConstant.BLOG_G, TipsConstant.BLOG_OPERATION_C);
        } else {
            req.setAttribute(PageConstant.BLOG_G, TipsConstant.BLOG_OPERATION_A);
        }
        req.getRequestDispatcher("/UserBlog/userBlog?id=" + bid + "&uid=" + uid).forward(req, resp);
    }

    /**
     * 做一个搜索功能
     */
    public void findBlogPage(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        String currentPage = req.getParameter("currentPage");
        String rows = req.getParameter("rows");

        //获取当前搜索的关键字
        String findBlog = req.getParameter("findBlog");
        //查询当前用户,然后调用方法获取博客列表
        PageBean<UserBlog> blogPageBean = blogService.findBlogPageBean(currentPage, rows, findBlog);
        req.removeAttribute(DataConstant.BLOG_C);
        req.setAttribute(DataConstant.BLOG_C, blogPageBean);
        //跳转回博客修改页面
        req.getRequestDispatcher("/findBlog.jsp").forward(req, resp);
    }

    /**
     * 用户收藏的文章页的展示
     */
    public void BlogLikeList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //先获取下ids
        List<Integer> blogIds = (List<Integer>) req.getAttribute("BlogIds");
        //调用方法楼,返回Blog集合
        List<UserBlog> list = blogService.findBlog(blogIds);
        if (list == null || list.size() == 0) {
            //设置下收藏夹的开关
            req.removeAttribute(DataConstant.BLOG_D);
            req.setAttribute(DataConstant.BLOG_D, "false");
        } else {
            //设置下收藏夹的开关
            req.removeAttribute(DataConstant.BLOG_D);
            req.setAttribute(DataConstant.BLOG_D, "true");

            req.removeAttribute(DataConstant.BLOG_E);
            req.setAttribute(DataConstant.BLOG_E, list);
        }
        req.getRequestDispatcher("/UserBlog/findBlogByPage").forward(req, resp);
    }

    /**
     * 博客详情页
     */
    public void Blog(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取各个数据
        String getId = req.getParameter("id");
        if (getId == null || "".equals(getId)) {
            resp.sendRedirect(req.getContextPath() + "/UserBlog/findUserBlog");
        } else {
            int id = Integer.parseInt(getId);
            User user = (User) req.getSession().getAttribute("user");
            if (user != null) {
                //调用SERVICE方法查询下用户有没有收藏这个文章
                req.setAttribute(DataConstant.BLOG_F, likeService.findLike(user.getId(), id));
            }
            //调用service方法查询并展示页面
            UserBlog blog = blogService.getUserBlog(id, 0);
            //这里是后续需要,上传到session域
            req.getSession().setAttribute(DataConstant.BLOG_G, blog);

            //获取用户数据然后上传
            User authorUser = userService.autoLogin(blog.getUid());
            req.setAttribute(DataConstant.USER_F, authorUser);


            //通过commentservice方法查询下相关的评论
            List<BlogComment> commentList = blogCommentService.getCommentList(id, 0);
            req.setAttribute(DataConstant.COMMENT_D, commentList);

            //接下来就是获取博客对应的图片了
            List<BlogImg> images = blogService.findBlogImages(getId);
            req.setAttribute(DataConstant.BLOG_IMG_A, images);

            req.getRequestDispatcher("/Blog.jsp").forward(req, resp);
        }
    }

    /**
     * 管理员文章修改的获取页面
     */
    public void managerUpdateBlog(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取上传的博客id
        String getid = req.getParameter("id");
        if (getid == null || "".equals(getid)) {
            resp.sendRedirect(req.getContextPath() + "/UserBlog/managerUpdateList");
        } else {
            int id = Integer.parseInt(getid);
            UserBlog blog = blogService.getUserBlog(id, 0);

            if (blog == null) {
                resp.sendRedirect(req.getContextPath() + "/UserBlog/managerUpdateList");
                //没有就跳转回博客初始页面
            }
            req.setAttribute(DataConstant.BLOG_H, blog);
            req.setAttribute(PageConstant.BLOG_C, "/managerUpdateList");
            req.setAttribute(PageConstant.BLOG_D, "managerUpdateList");
            req.setAttribute(PageConstant.BLOG_E, "managerUpdateBlog");
            req.getRequestDispatcher("/updateBlog.jsp").forward(req, resp);
            //跳转回博客修改页面
        }
    }

    /**
     * 管理员文章修改列表获取方法
     */
    public void managerUpdateList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        String currentPage = req.getParameter("currentPage");
        String rows = req.getParameter("rows");

        //调用service获取查询到的博客列表
        PageBean<UserBlog> blogPageBean = blogService.findBlogByPage(null, currentPage, rows, null);

        //数据存储
        req.setAttribute(DataConstant.BLOG_I, blogPageBean);
        req.getRequestDispatcher("/ManagerUpdate.jsp").forward(req, resp);
    }

    /**
     * 用户文章审核用方法
     */
    public void examineBlog(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        //先获取下博客的id
        String[] blogIds = req.getParameterValues("blogId");
        //校验一下
        req.removeAttribute(PageConstant.BLOG_F);
        if (blogIds == null || blogIds.length == 0) {
            //返回审核界面
            //返回数据有误
            req.setAttribute(PageConstant.BLOG_F, TipsConstant.BLOG_OPERATION_A);
        } else {
            if (blogService.changeBlogs(blogIds, SqlConstant.STATUS_B)) {
                req.setAttribute(PageConstant.BLOG_F, TipsConstant.BLOG_OPERATION_B);
            } else {
                req.setAttribute(PageConstant.BLOG_F, TipsConstant.BLOG_OPERATION_A);
            }
        }
        req.getRequestDispatcher("/UserBlog/examineList").forward(req, resp);
    }

    /**
     * 文章审核列表展示
     */
    public void examineList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String currentPage = req.getParameter("currentPage");
        String rows = req.getParameter("rows");

        //调用service获取查询到的博客列表
        PageBean<UserBlog> blogPageBean = blogService.findBlogByPage(null, currentPage, rows, SqlConstant.STATUS_A);

        //数据存储
        req.setAttribute(DataConstant.BLOG_J, blogPageBean);
        req.getRequestDispatcher("/ExamineBlog.jsp").forward(req, resp);
    }


    /**
     * 博客删除方法
     */
    public void deleteBlog(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        //获取下操作完成后要跳转的地方
        String afterDelete = req.getParameter("afterDelete");
        //获取得到的id对象
        String getid = req.getParameter("id");
        if (getid != null && !"".equals(getid)) {
            int id = Integer.parseInt(getid);
            //调用方法
            blogService.deleteBlog(id);
            //返回主界面
        }
        resp.sendRedirect(req.getContextPath() + "/UserBlog/" + afterDelete);
    }

    /**
     * 博客更新方法
     */
    public void updateBlog(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //直接封装
        String afterBack = req.getParameter("afterBack");
        Map<String, String[]> map = req.getParameterMap();
        UserBlog blog = new UserBlog();
        try {
            //将获取的博客内容封装到文件中
            BeanUtils.populate(blog, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        req.removeAttribute(PageConstant.BLOG_G);
        //导入service处理
        if (blogService.updateBlog(blog)) {
            req.setAttribute(PageConstant.BLOG_G, TipsConstant.BLOG_OPERATION_B);
        } else {
            req.setAttribute(PageConstant.BLOG_G, TipsConstant.BLOG_OPERATION_A);
        }
        req.getRequestDispatcher("/UserBlog/" + afterBack).forward(req, resp);

    }

    /**
     * 用户博客修改页的回写操作
     */
    public void userBlog(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取上传的用户id和博客id
        String getId = req.getParameter("id");
        String getuid = req.getParameter("uid");
        if (getId == null || getuid == null || "".equals(getId) || "".equals(getuid)) {
            resp.sendRedirect(req.getContextPath() + "/UserBlog/findUserBlog");
        } else {
            int id = Integer.parseInt(getId);
            int uid = Integer.parseInt(getuid);
            UserBlog blog = blogService.getUserBlog(id, uid);
            if (blog == null) {
                resp.sendRedirect(req.getContextPath() + "/UserBlog/findUserBlog");
                //没有就跳转回博客初始页面
            }

            req.setAttribute(DataConstant.BLOG_H, blog);

            //博客返回和前进操作跳转用的内容获取和存储
            req.setAttribute(PageConstant.BLOG_E, "userBlog");
            req.setAttribute(PageConstant.BLOG_C, "/userBlog");
            req.setAttribute(PageConstant.BLOG_D, "findUserBlog");

            //专栏相关内容的获取
            String crows = req.getParameter("crows");
            String ccurrentPage = req.getParameter("ccurrentPage");
            String columnId = req.getParameter("columnId");

            PageBean<Column> columnPageBean = columnService.findColumnByPage(crows, ccurrentPage, columnId);
            req.setAttribute(DataConstant.COLUMN_A, columnPageBean);
            req.setAttribute(DataConstant.COLUMN_B, columnId);
            //跳转回博客修改页面
            req.getRequestDispatcher("/updateBlog.jsp").forward(req, resp);
        }
    }

    /**
     * 用户博客展示方法
     */
    public void findUserBlog(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        ;
        //获取下当前用户
        User user = (User) req.getSession().getAttribute("user");
        //获取下博客有的标签
        String labelPrior = req.getParameter("labelPrior");
        //查询当前用户,然后调用方法获取博客列表
        req.setAttribute(DataConstant.BLOG_K, blogService.findUserBlog(req.getParameter("currentPage"), req.getParameter("rows"), user.getId(), null));
        //直接获取下该用户目前有的专栏数据,然后获取展示
        req.setAttribute(DataConstant.LABEL_PAGE, labelService.getLabelPage(user.getId(), labelPrior));
        req.setAttribute(DataConstant.LABEL_PRIOR, labelPrior);
        //跳转回博客修改页面
        req.getRequestDispatcher("/UserBlog.jsp").forward(req, resp);
    }

    /**
     * 主页博客展示方法
     */
    public void findBlogByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String currentPage = req.getParameter("currentPage");
        //当前页码
        String rows = req.getParameter("rows");
        //每页显示条数
        String crows = req.getParameter("crows");
        String ccurrentPage = req.getParameter("ccurrentPage");

        String columnId = req.getParameter("columnId");


        //调用service获取查询到的博客列表
        PageBean<UserBlog> blogPageBean = blogService.findBlogByPage(columnId, currentPage, rows, SqlConstant.STATUS_B);
        PageBean<Column> columnPageBean = columnService.findColumnByPage(crows, ccurrentPage, columnId);
        //数据存储
        req.setAttribute(DataConstant.BLOG_L, blogPageBean);
        req.setAttribute(DataConstant.COLUMN_A, columnPageBean);
        req.setAttribute(DataConstant.COLUMN_B, columnId);
        req.getRequestDispatcher("/Home.jsp").forward(req, resp);
    }

    /**
     * 博客添加用方法
     */
    public void addBlog(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {


        UserBlog blog = new UserBlog();
        blog.setTitle(req.getParameter("title"));
        blog.setContent(req.getParameter("content"));
        //获取上传到session的用户
        User user = (User) req.getSession().getAttribute(DataConstant.USER_A);
        //将用户id添加的文章中
        blog.setUid(user.getId());

        String addColumn = req.getParameter("addColumn");
        //要添加的自定义专栏
        String addColumnId = req.getParameter("addColumnId");
        //要添加的已有专栏id
        String columnId = req.getParameter("columnId");
        //要添加的自定义专栏的前驱
        req.removeAttribute(PageConstant.BLOG_H);
        //调用service方法来添加文章
        req = blogService.addBlog(blog, addColumn, addColumnId, columnId, req);
        req.getRequestDispatcher("/Column/columnPage").forward(req, resp);
    }

}
